﻿using Login.Database.JsonConvert;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;


namespace Login.DataAccess
{
    public interface IRepository<T>
    {
        T Find(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includes);
    }
    public class Repository<T> : IRepository<T>
       where T : class
    {

        protected DbContext Context = null;
        public string TempJsonData = null;


        public Repository()
        {
            Context = new Database.LoginContext();
        }
        public Repository(DbContext context)
        {
            Context = context;
        }
        protected DbSet<T> DbSet
        {
            get
            {
                return Context.Set<T>();
            }
        }
        public virtual T Find(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includes)
        {
            var dbSet = GetInclude(DbSet.Where(predicate), includes);
            var result = dbSet.FirstOrDefault();
            TempJsonData =
            JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, ContractResolver = new DynamicEntityContractResolver() });
            return result;
        }

        private IQueryable<T> GetInclude(IQueryable<T> dbSet, params Expression<Func<T, object>>[] includes)
        {
            if (includes.Length > 0)
            {
                foreach (var expression in includes)
                {
                    dbSet = dbSet.Include(expression);
                }
            }
            return dbSet;
        }
    }
}
